package jdbc;

import util.JdbcQueryCallBack;

import java.sql.*;
import java.util.Map;

/**
 * Created by Zhou_Bing on 2018/9/11.
 * <p>
 * jdbc工具类
 */
public class JdbcUtil {

    private static final String URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF8";

    public static void query(String sql, JdbcQueryCallBack callBack) {
        Connection conn = null;
        try {
            conn = getConnect();
            Statement stmt = conn.createStatement();

            ResultSet resultSet = stmt.executeQuery(sql);
            callBack.execute(resultSet);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static boolean execute(String sql) {
        Connection conn = null;
        try {
            conn = getConnect();
            Statement stmt = conn.createStatement();
            return stmt.execute(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static Connection getConnect() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.jdbc.Driver");
        return DriverManager.getConnection(URL, "root", "root");
    }

}
